package com.example.controller;

import com.example.common.RequireDataPermission;
import com.example.common.RequirePermission;
import com.example.common.Result;
import com.example.entity.Role;
import com.example.entity.User;
import com.example.service.AdminService;
import com.example.service.PermissionInitService;
import com.example.service.RolePermissionService;
import com.example.vo.MenuVO;
import com.example.vo.UserWithRoleVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/admin")
@CrossOrigin
public class AdminController {
    
    @Autowired
    private AdminService adminService;

    @Autowired
    private PermissionInitService permissionInitService;

    @Autowired
    private RolePermissionService rolePermissionService;
    
    // 获取所有用户
    @GetMapping("/users")
    @RequirePermission("admin:user:list")
    public Result<List<UserWithRoleVO>> getAllUsers() {
        return adminService.getAllUsers();
    }
    
    // 根据角色获取用户列表
    @GetMapping("/users/by-role/{roleId}")
    @RequirePermission("admin:user:list")
    public Result<List<UserWithRoleVO>> getUsersByRole(@PathVariable Long roleId) {
        return adminService.getUsersByRole(roleId);
    }
    
    // 新增用户
    @PostMapping("/users")
    @RequirePermission("admin:user:add")
    @com.example.common.OperationLog(
        module = "用户管理",
        operationType = "CREATE",
        description = "新增用户",
        recordParams = true,
        businessType = "USER"
    )
    public Result<Void> addUser(@RequestBody User user) {
        return adminService.addUser(user);
    }
    
    // 更新用户
    @PutMapping("/users/{id}")
    @RequirePermission("admin:user:update")
    @RequireDataPermission(value = RequireDataPermission.DataPermissionType.DEPARTMENT_AND_SUB,
                          resourceType = "user",
                          description = "只能更新同部门及子部门的用户信息")
    @com.example.common.OperationLog(
        module = "用户管理",
        operationType = "UPDATE",
        description = "修改用户信息",
        recordParams = true,
        businessType = "USER"
    )
    public Result<Void> updateUser(@PathVariable Long id, @RequestBody User user) {
        return adminService.updateUser(id, user);
    }
    
    // 删除用户
    @DeleteMapping("/users/{id}")
    @RequirePermission("admin:user:delete")
    public Result<Void> deleteUser(@PathVariable Long id) {
        return adminService.deleteUser(id);
    }
    
    // 获取单个用户信息
    @GetMapping("/users/{id}")
    @RequirePermission("admin:user:view")
    @RequireDataPermission(value = RequireDataPermission.DataPermissionType.DEPARTMENT_AND_SUB,
                          resourceType = "user",
                          description = "只能查看同部门及子部门的用户信息")
    public Result<User> getUserById(@PathVariable Long id) {
        return adminService.getUserById(id);
    }
    
    // 获取用户角色
    @GetMapping("/user-roles/{userId}")
    @RequirePermission("admin:user:role:view")
    public Result<List<Long>> getUserRoles(@PathVariable Long userId) {
        return adminService.getUserRoles(userId);
    }
    
    // 分配角色
    @PostMapping("/assign-role")
    @RequirePermission("admin:user:role:assign")
    public Result<Void> assignRole(@RequestParam Long userId, @RequestParam Long roleId) {
        return adminService.assignRole(userId, roleId);
    }
    
    // 分配菜单
    @PostMapping("/assign-menu")
    @RequirePermission("admin:role:menu:assign")
    public Result<Void> assignMenu(@RequestParam Long roleId, @RequestBody List<Long> menuIds) {
        return adminService.assignMenu(roleId, menuIds);
    }
    
    // 获取所有角色
    @GetMapping("/roles")
    @RequirePermission("admin:role:list")
    public Result<List<Role>> getAllRoles() {
        return adminService.getAllRoles();
    }
    
    // 新增角色
    @PostMapping("/roles")
    @RequirePermission("admin:role:add")
    public Result<Void> addRole(@RequestBody Role role) {
        return adminService.addRole(role);
    }
    
    // 更新角色
    @PutMapping("/roles/{id}")
    @RequirePermission("admin:role:update")
    public Result<Void> updateRole(@PathVariable Long id, @RequestBody Role role) {
        return adminService.updateRole(id, role);
    }
    
    // 删除角色
    @DeleteMapping("/roles/{id}")
    @RequirePermission("admin:role:delete")
    public Result<Void> deleteRole(@PathVariable Long id) {
        return adminService.deleteRole(id);
    }
    
    // 获取单个角色信息
    @GetMapping("/roles/{id}")
    @RequirePermission("admin:role:view")
    public Result<Role> getRoleById(@PathVariable Long id) {
        return adminService.getRoleById(id);
    }
    
    // 获取所有菜单
    @GetMapping("/menus")
    @RequirePermission("admin:menu:list")
    public Result<List<MenuVO>> getAllMenus() {
        return adminService.getAllMenus();
    }
    
    // 获取角色菜单
    @GetMapping("/role-menus/{roleId}")
    @RequirePermission("admin:role:menu:view")
    public Result<List<Long>> getRoleMenus(@PathVariable Long roleId) {
        return adminService.getRoleMenus(roleId);
    }
    
    // 为用户管理页面添加的API端点
    
    // 获取用户的角色信息（返回角色详情而不是ID）
    @GetMapping("/users/{userId}/roles")
    @RequirePermission("admin:user:role:view")
    public Result<List<Role>> getUserRoleDetails(@PathVariable Long userId) {
        return adminService.getUserRoleDetails(userId);
    }
    
    // 批量分配角色给用户
    @PostMapping("/users/{userId}/roles")
    @RequirePermission("admin:user:role:assign")
    public Result<Void> assignRolesToUser(@PathVariable Long userId, @RequestBody List<Long> roleIds) {
        return adminService.assignRolesToUser(userId, roleIds);
    }

    // 检查并创建缺失的权限
    @PostMapping("/system/check-permissions")
    @RequirePermission("admin:system:manage")
    public Result<String> checkAndCreatePermissions() {
        try {
            permissionInitService.checkAndCreateMissingPermissions();
            return Result.success("权限检查完成，已创建缺失的权限");
        } catch (Exception e) {
            return Result.error("权限检查失败：" + e.getMessage());
        }
    }

    // 检查并修复角色权限菜单一致性
    @PostMapping("/roles/{roleId}/check-consistency")
    @RequirePermission("admin:role:manage")
    public Result<String> checkRolePermissionConsistency(@PathVariable Long roleId) {
        return rolePermissionService.checkAndFixConsistency(roleId);
    }

} 